//
//  MSProShowerVC.m
//  MS
//
//  Created by Yuan on 13-2-8.
//  Copyright (c) 2013年 He Yuan. All rights reserved.
//

#import "MSProShowerVC.h"

#import "WaterFlowView.h"
#import "ImageViewCell.h"
#import "UIImageView+WebCache.h"
#import "LoadingMoreFooterView.h"
#import "EGORefreshTableHeaderView.h"
#import "MSProShowerTopBar.h"

#import "CustomSegmentedControl.h"

#import "MSShowerDetailVC.h"


@interface MSProShowerVC ()<WaterFlowViewDelegate,WaterFlowViewDataSource,UIScrollViewDelegate,EGORefreshTableHeaderDelegate,CustomSegmentedControl>
{
    MSProShowerTopBar *topBar;
    
    WaterFlowView *waterFlow;
    NSMutableArray *arrayData;
    
    NSInteger page;
    BOOL nextpage;
    
    BOOL _reloading;
    EGORefreshTableHeaderView *_refreshHeaderView;
    
    BOOL isRequesting;
    
    ProShowerSortType showerType;
}
@property(nonatomic,retain) LoadingMoreFooterView *loadFooterView;
@property(nonatomic,retain) WaterFlowView *waterFlow;
@property(nonatomic,retain) NSMutableArray *arrayData;

- (void)dataSourceDidLoad;

- (void)dataSourceDidError;

@end

@implementation MSProShowerVC
@synthesize loadFooterView = _loadFooterView;
@synthesize waterFlow = _waterFlow;
@synthesize arrayData = _arrayData;


- (id)init
{
    self = [super init];
    if (self)
    {
        showerType = ProShowerTypeLastest;
        nextpage = YES;
        page = 1;
        _arrayData = [[NSMutableArray alloc] init];
    }
    return self;
}

-(void)loadView
{
    [super loadView];

    topBar = [[MSProShowerTopBar alloc]initWithFrame:CGRectZero delegate:self];
    [self.view addSubview:topBar];
    
    _waterFlow = [[WaterFlowView alloc] initWithFrame:CGRectMake(0, topBar.frame.size.height, topBar.frame.size.width,self.view.frame.size.height - topBar.frame.size.height)];
    _waterFlow.waterFlowViewDelegate = self;
    _waterFlow.waterFlowViewDatasource = self;
    _waterFlow.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleTopMargin;
    _waterFlow.delegate = self;
    _waterFlow.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_waterFlow];
    
    _loadFooterView = [[LoadingMoreFooterView alloc]initWithFrame:CGRectMake(0, 0, waterFlow.frame.size.width, 44.f)];
    _loadFooterView.hidden = NO;
    [_waterFlow addSubview:_loadFooterView];
    
    
    if (_refreshHeaderView == nil)
    {
		_refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.waterFlow.bounds.size.height, self.view.frame.size.width, self.waterFlow.bounds.size.height)];
		_refreshHeaderView.delegate = self;
		[self.waterFlow addSubview:_refreshHeaderView];
	}
	
	//  update the last update date
	[_refreshHeaderView refreshLastUpdatedDate];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}


- (void)viewDidLoad
{
    [super viewDidLoad];

    [self setTitle:HYLocalizedString(@"专业发型秀") showBackButton:YES];    
}

-(void)configureViews:(BOOL)animation
{
    [super configureViews:animation];
    
    [self performSelector:@selector(ViewFrashData) withObject:nil afterDelay:0.3];
}


-(void)ViewFrashData
{
    [_waterFlow setContentOffset:CGPointMake(0,-75) animated:YES];
    [self performSelector:@selector(doneManualRefresh) withObject:nil afterDelay:0.4];
}

-(void)doneManualRefresh
{
    [_refreshHeaderView egoRefreshScrollViewDidScroll:_waterFlow];
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:_waterFlow];
}


#pragma CustomSegmentedControlDelegate methord
-(void)didSelectIndex:(NSUInteger)selectedIndex withSegmentControl:(CustomSegmentedControl*)segmentControl
{    
    showerType = selectedIndex;
    nextpage = YES;
    page = 1;
    [self ViewFrashData];
}

-(void)changeMode:(UIButton *)btn
{
    UIViewAnimationOptions option = btn.selected?UIViewAnimationOptionTransitionFlipFromRight:UIViewAnimationOptionTransitionFlipFromLeft;
    [UIView transitionWithView:btn duration:0.3 options:option animations:^(void){
    }completion:^(BOOL finished){
        btn.selected = !btn.selected;
    }];
}


-(void)requestData
{
    if (isRequesting || !nextpage)return;
            
    isRequesting = YES;
    
    NSDictionary *p =  [NSDictionary dictionaryWithObjectsAndKeys:
                        [NSNumber numberWithInt:showerType],@"hot",
                        [NSNumber numberWithInteger:page],@"page",
                        nil];
    [WebService getRequestAction:APIZhuanYeList
                           param:p
                         success:^(NSDictionary *info,NSError *error)
     {
         [self performSelectorOnMainThread:@selector(doneLoadingTableViewData) withObject:nil waitUntilDone:YES];
         if (error == nil)
         {
             if (info)
             {
                 if (page == 1)[_arrayData removeAllObjects];
                 
                 nextpage = [[info objectForKey:@"nextpage"] intValue];
             
                 NSArray *result = [info objectForKey:@"result"];
                 
                 if (result && [result isKindOfClass:[NSArray class]] &&[result count]>0)
                 {
                     [_arrayData addObjectsFromArray:result];
                     [UIView animateWithDuration:0.2 animations:^(void){
                         _waterFlow.alpha = 0.0f;
                     } completion:^(BOOL f){
                         [self dataSourceDidLoad];
                         [UIView animateWithDuration:0.3 animations:^(void){
                             _waterFlow.alpha = 1.0f;
                         }];
                     }];
                 }
                 page++;
             }
         }
         [MSTool showError:error];
         isRequesting = NO;
     } failure:^(id info ,NSError *error){
         [MSTool showError:error];
         isRequesting = NO;
         [self performSelectorOnMainThread:@selector(doneLoadingTableViewData) withObject:nil waitUntilDone:YES];
     } progress:nil];
}


#pragma mark -
#pragma mark Data Source Loading / Reloading Methods
//下拉刷新就调用
- (void)reloadTableViewDataSource
{
	_reloading = YES;
    nextpage = YES;
    page = 1;
    [self requestData];
}

- (void)doneLoadingTableViewData
{
	//  model should call this when its done loading
	_reloading = NO;
    NSDate * date = [NSDate date];
    [[NSUserDefaults standardUserDefaults] setValue:date forKey:@"EGORefreshTableView_MSProShower_LastRefresh"];
    [[NSUserDefaults standardUserDefaults] synchronize];
	[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.waterFlow];
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)sc{
	[_refreshHeaderView egoRefreshScrollViewDidScroll:sc];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)sc willDecelerate:(BOOL)decelerate{
	[_refreshHeaderView egoRefreshScrollViewDidEndDragging:sc];
}


#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	
	[self reloadTableViewDataSource];
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	
	return _reloading; // should return if data source model is reloading
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view
{
    NSDate *date =  [[NSUserDefaults standardUserDefaults] valueForKey:@"EGORefreshTableView_MSProShower_LastRefresh"];
    if (date == nil)date = [NSDate date];
	return date; // should return date data source was last changed
}


- (void)dataSourceDidLoad
{
    [_waterFlow reloadData];
}

- (void)dataSourceDidError
{
    [_waterFlow reloadData];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    float bottomEdge = scrollView.contentOffset.y + scrollView.frame.size.height;
    if (bottomEdge >=  floor(scrollView.contentSize.height) )
    {
        if (!self.waterFlow.hidden)
        {
            _loadFooterView.frame = CGRectMake(0, bottomEdge, _waterFlow.frame.size.width, 44);
            if (nextpage)
            {
                _loadFooterView.hidden = NO;
                [self requestData];
            }
            else
            {
                _loadFooterView.hidden = YES;
            }
        }
        NSLog(@"load more");
    }
}

#pragma mark WaterFlowViewDataSource
- (NSInteger)numberOfColumsInWaterFlowView:(WaterFlowView *)waterFlowView
{
    return 3;
}

- (NSInteger)numberOfAllWaterFlowView:(WaterFlowView *)waterFlowView{
    
    return [_arrayData count];
}

- (UIView *)waterFlowView:(WaterFlowView *)waterFlowView cellForRowAtIndexPath:(IndexPath *)indexPath
{
    ImageViewCell *view = [[ImageViewCell alloc] initWithIdentifier:nil];
    return view;
}

-(void)waterFlowView:(WaterFlowView *)waterFlowView  relayoutCellSubview:(UIView *)view withIndexPath:(IndexPath *)indexPath
{
    int arrIndex = indexPath.row * waterFlowView.columnCount + indexPath.column;
    NSDictionary *object = [_arrayData objectAtIndex:arrIndex];
    ImageViewCell *imageViewCell = (ImageViewCell *)view;
    imageViewCell.indexPath = indexPath;
    imageViewCell.columnCount = waterFlowView.columnCount;
    [imageViewCell relayoutViews];
    NSString *imageUrl = [object objectForKey:@"thumb"];
    if (imageUrl&&[imageUrl length]>0)
    {
        NSURL *URL = [NSURL URLWithString:imageUrl];
        [(ImageViewCell *)view setImageWithURL:URL placeholderImage:[UIImage imageNamed:@""] ];
    }
    else
    {
        [(ImageViewCell *)view setImageWithURL:nil placeholderImage:[UIImage imageNamed:@""]];
    }
}

#pragma mark WaterFlowViewDelegate
- (CGFloat)waterFlowView:(WaterFlowView *)waterFlowView heightForRowAtIndexPath:(IndexPath *)indexPath
{
    int arrIndex = indexPath.row * waterFlowView.columnCount + indexPath.column;
    NSDictionary *dict = [_arrayData objectAtIndex:arrIndex];
    float width = 0.0f;
    float height = 0.0f;
    if (dict)
    {
        NSObject *width_ = [dict objectForKey:@"width"];
        if (width_ && ![width_ isKindOfClass:[NSNull class]] && [width_ isKindOfClass:[NSString class]])
        {
            width = [(NSString*)width_ floatValue];
        }
        else
        {
            width = 100;
        }
        
        NSObject *height_ = [dict objectForKey:@"height"];
        if (height_ && ![height_ isKindOfClass:[NSNull class]] && [height_ isKindOfClass:[NSString class]])
        {
            height = [(NSString*)height_ floatValue];
        }
        else
        {
            height = 100;
        }
    }
    return waterFlowView.cellWidth * (height/width);
}

- (void)waterFlowView:(WaterFlowView *)waterFlowView didSelectRowAtIndexPath:(IndexPath *)indexPath
{
    NSLog(@"indexpath row == %d,column == %d",indexPath.row,indexPath.column);
    int arrIndex = indexPath.row * waterFlowView.columnCount + indexPath.column;
    MSShowerDetailVC *vc = [[MSShowerDetailVC alloc]initWithDatas:_arrayData currentIndex:arrIndex];
    [self.navigationController pushViewController:vc animated:YES];    
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
